import React, { useState } from 'react'
import { SearchBar, List } from 'antd-mobile'
import { debounce } from 'lodash'
import { useDispatch, useSelector } from 'react-redux'
import { StateType } from '../../store/reducer'
import request from '../../utils/request'
const App = () => {
	const historyList = useSelector((state: StateType) => state.historyList)
	const [isSearch, setIsSearch] = useState(false)
	const [list, setList] = useState<any[]>([])
	const dispatch = useDispatch()
	const handleSearch = debounce((value) => {
		if (value !== '') {
			setIsSearch(true)
			request({
				url: '/api/search',
				params: {
					value: value
				}
			}).then(resp => {
				console.log(resp.data);
				setList(resp.data.data)
			})
		} else {
			setIsSearch(false)
		}
	}, 400)

	return (
		<>
			<SearchBar onChange={(value) => handleSearch(value)}></SearchBar>
			{
				isSearch ? <List>
					{
						list.map((v) => {
							return <List.Item key={v.id}>
								{v.title}
							</List.Item>
						})
					}
				</List> : <div>
					<h3 style={{ display: 'flex', justifyContent: 'space-between' }}>
						<span>历史搜索记录</span>
						<span onClick={() => dispatch({ type: 'CLEAR_HISTORY_LIST' })}>清空</span>
					</h3>
					{
						historyList.length > 0 ? historyList.map((v, i) => {
							return <span key={i} style={{ padding: '0 20px' }}>{v}</span>
						}) : '暂无历史记录'
					}
				</div>
			}
		</>
	)
}


export default App